<template>
  <div class="user-information-page">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="个人资料" name="information">
        <el-form ref="formRef" class="info-form" :model="form" label-width="100px">
          <el-form-item label="头像">
            <div class="avatar-box" @click="handleShowAvatarDialog">
              <el-avatar :src="form?.avatar" :size="80">
                {{ form?.nickName?.charAt(0) || 'U' }}
              </el-avatar>
              <div class="avatar-overlay">
                <i class="i-carbon-edit"></i>
              </div>
            </div>
          </el-form-item>

          <el-form-item label="邮箱">
            <el-input v-model="form.email" disabled />
          </el-form-item>

          <el-form-item label="昵称">
            <el-input v-model="form.nickName" placeholder="请输入昵称" />
          </el-form-item>

          <el-form-item label="手机号码">
            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" />
          </el-form-item>

          <el-form-item label="性别">
            <el-radio-group v-model="form.sex">
              <el-radio label="0">男</el-radio>
              <el-radio label="1">女</el-radio>
              <el-radio label="2">未知</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="生日">
            <el-date-picker
              v-model="form.birthday"
              value-format="YYYY-MM-DD"
              type="date"
              placeholder="选择日期"
              class="w-full"
            />
          </el-form-item>

          <el-form-item label="个人简介">
            <el-input
              v-model="form.remark"
              type="textarea"
              :rows="4"
              placeholder="请输入个人简介"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="updating" @click="handleUpdateInformation">
              保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="修改密码" name="editPassword">
        <el-form
          ref="passwordFormRef"
          :rules="passwordFormRules"
          class="password-form"
          :model="passwordForm"
          label-width="100px"
        >
          <el-form-item prop="oldPassword" label="原密码">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
            />
          </el-form-item>

          <el-form-item prop="newPassword" label="新密码">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码（6-20位）"
              show-password
            />
          </el-form-item>

          <el-form-item prop="confirmPassword" label="确认密码">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="updatingPassword" @click="handleUpdatePassword">
              修改密码
            </el-button>
            <el-button @click="resetPasswordForm">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 头像裁剪对话框 -->
    <el-dialog
      v-model="avatarDialogVisible"
      title="修改头像"
      width="500px"
    >
      <div class="avatar-upload-container">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="handleAvatarUpload"
          accept="image/*"
        >
          <el-avatar v-if="form.avatar" :src="form.avatar" :size="150" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
          <div class="upload-hint">点击上传新头像</div>
        </el-upload>

        <div class="upload-tips">
          <p>支持 JPG、PNG 格式</p>
          <p>建议图片尺寸为 200x200 像素</p>
          <p>文件大小不超过 2MB</p>
        </div>
      </div>

      <template #footer>
        <el-button @click="avatarDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="uploading" @click="handleSaveAvatar">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

definePageMeta({
  layout: 'userCenter',
  middleware: 'auth'
})

const userStore = useUserStore()
const router = useRouter()

// 状态
const activeTab = ref('information')
const updating = ref(false)
const updatingPassword = ref(false)
const uploading = ref(false)
const avatarDialogVisible = ref(false)
const uploadedAvatar = ref('')

// 表单数据
const form = ref({
  userId: null,
  nickName: '',
  phonenumber: '',
  email: '',
  sex: '2',
  birthday: '',
  remark: '',
  avatar: ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单引用
const formRef = ref()
const passwordFormRef = ref()

// 密码表单验证规则
const passwordFormRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const data = await $fetch('/dev-api/system/user/profile', {
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      }
    })

    if (data.code === 200) {
      form.value = {
        ...data.data,
        sex: String(data.data.sex || '2'),
        birthday: data.data.birthday || ''
      }
    }
  } catch (error: any) {
    console.error('获取用户信息失败:', error)
    ElMessage.error(error.data?.msg || '获取用户信息失败')
  }
}

// 更新个人信息
const handleUpdateInformation = async () => {
  updating.value = true
  try {
    const data = await $fetch('/dev-api/system/user/profile', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        nickName: form.value.nickName,
        phonenumber: form.value.phonenumber,
        sex: form.value.sex,
        birthday: form.value.birthday,
        remark: form.value.remark
      }
    })

    if (data.code === 200) {
      ElMessage.success('修改成功')
      // 刷新用户信息
      await userStore.getUserInfo(true)  // 强制刷新用户信息
    } else {
      ElMessage.error(data.msg || '修改失败')
    }
  } catch (error: any) {
    console.error('更新用户信息失败:', error)
    ElMessage.error(error.data?.msg || '修改失败')
  } finally {
    updating.value = false
  }
}

// 更新密码
const handleUpdatePassword = async () => {
  try {
    await passwordFormRef.value.validate()

    updatingPassword.value = true

    const data = await $fetch('/dev-api/system/user/profile/updatePwd', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      params: {
        oldPassword: passwordForm.value.oldPassword,
        newPassword: passwordForm.value.newPassword
      }
    })

    if (data.code === 200) {
      ElMessage.success('密码修改成功，请重新登录')
      resetPasswordForm()
      // 延迟跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 1500)
    } else {
      ElMessage.error(data.msg || '修改失败')
    }
  } catch (error: any) {
    if (error.data) {
      ElMessage.error(error.data.msg || '修改失败')
    }
  } finally {
    updatingPassword.value = false
  }
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value?.resetFields()
  passwordForm.value = {
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
}

// 显示头像上传对话框
const handleShowAvatarDialog = () => {
  uploadedAvatar.value = ''
  avatarDialogVisible.value = true
}

// 上传前验证
const beforeAvatarUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 处理头像上传
const handleAvatarUpload = async (options: any) => {
  const formData = new FormData()
  formData.append('file', options.file)

  try {
    uploading.value = true
    const data = await $fetch('/dev-api/common/upload', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: formData
    })

    if (data.code === 200) {
      uploadedAvatar.value = data.url
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(data.msg || '上传失败')
    }
  } catch (error: any) {
    console.error('上传失败:', error)
    ElMessage.error(error.data?.msg || '上传失败')
  } finally {
    uploading.value = false
  }
}

// 保存头像
const handleSaveAvatar = async () => {
  if (!uploadedAvatar.value) {
    ElMessage.warning('请先上传头像')
    return
  }

  try {
    uploading.value = true

    const data = await $fetch('/dev-api/system/user/profile/avatar', {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${userStore.token}`
      },
      body: {
        avatar: uploadedAvatar.value
      }
    })

    if (data.code === 200) {
      form.value.avatar = uploadedAvatar.value
      ElMessage.success('头像修改成功')
      avatarDialogVisible.value = false
      // 刷新用户信息
      await userStore.getUserInfo(true)  // 强制刷新用户信息
    } else {
      ElMessage.error(data.msg || '修改失败')
    }
  } catch (error: any) {
    console.error('保存头像失败:', error)
    ElMessage.error(error.data?.msg || '保存失败')
  } finally {
    uploading.value = false
  }
}

// 页面加载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.user-information-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.info-form,
.password-form {
  margin-top: 20px;
  max-width: 600px;
}

.avatar-box {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-box:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay i {
  font-size: 24px;
  color: white;
}

.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader-icon {
  font-size: 50px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: all 0.3s;
}

.avatar-uploader-icon:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.upload-hint {
  margin-top: 10px;
  font-size: 14px;
  color: #606266;
}

.upload-tips {
  text-align: center;
  font-size: 12px;
  color: #909399;
  line-height: 1.8;
}

:deep(.el-form-item__label) {
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.1);
}

:deep(.el-textarea__inner) {
  background-color: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input__inner) {
  color: rgba(255, 255, 255, 0.8);
}

:deep(.el-input.is-disabled .el-input__wrapper) {
  background-color: rgba(255, 255, 255, 0.05);
}
</style>
